//
//  Utility.m
//  ErpApp2.0
//
//  Created by EricWei on 14-3-17.
//
//

#import "Utility.h"
#import "AppDelegate.h"
static const char _base64EncodingTable[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const short _base64DecodingTable[256] = {
    -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -2, -1, -1, -2, -2,
    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
    -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, -2, -2, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, -2, -2, -2,
    -2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -2, -2, -2, -2, -2,
    -2, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -2, -2, -2, -2, -2,
    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
    -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2
};
@implementation Utility
#define     LocalStr_None           @""

//判断字符串是否为空
+ (BOOL) isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    
    if ([string isEqualToString:@"(null)"] || [string isEqualToString:@"<null>"] || [string isEqualToString:@"null"]) {
        return YES;
    }
    
    return NO;
}

+(NSString *)GetStrByNull:(NSString *)str returnStr:(NSString *)returnStr
{
    if ([self isBlankString:str])
        return returnStr;
    return str;
}
//去除空格
+(NSString *)getString:(NSString *)string
{
    return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

+(void)setExtraCellLineHidden: (UITableView *)tableView
{
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
}


//处理空字符串
+(NSString *)doEmptyString:(NSString*)str
{
    
    if ([self isBlankString:str] || [str isEqualToString:@"(null)"]) {
        return @"";
    }
    return str;
}



#pragma  mark - 设置返回按钮
+(NSString*)DateFromater:(NSDate*)current strDateFromater:(NSString *)str
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:str];
    //用[NSDate date]可以获取系统当前时间
    return  [dateFormatter stringFromDate:current];
    
}
+(NSInteger)geTimestamp:(NSString *)str{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormatter dateFromString:str];
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    return timeSp;
}
/**
 时间戳转换时间
 
 @param time <#time description#>
 @return <#return value description#>
 */
+ (NSString *)getTimeString:(NSInteger)time{
    NSDateFormatter *stampFormatter = [[NSDateFormatter alloc] init];
    [stampFormatter setDateFormat:@"MM-dd"];
    //以 1970/01/01 GMT为基准，然后过了secs秒的时间
    NSDate *stampDate2 = [NSDate dateWithTimeIntervalSince1970:time];
    return [stampFormatter stringFromDate:stampDate2];
}
/**
 获取当前时间

 @return <#return value description#>
 */
+(NSString*)getCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
//    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}
/**
 时间戳转换时间
 
 @param time <#time description#>
 @return <#return value description#>
 */
+ (NSString *)getAllTimeString:(NSInteger)time{
    NSDateFormatter *stampFormatter = [[NSDateFormatter alloc] init];
    [stampFormatter setDateFormat:@"yyy-MM-dd"];
    //以 1970/01/01 GMT为基准，然后过了secs秒的时间
    NSDate *stampDate2 = [NSDate dateWithTimeIntervalSince1970:time];
    return [stampFormatter stringFromDate:stampDate2];
}
/**
 首页时间戳转换时间
 
 @param time <#time description#>
 @return <#return value description#>
 */
+ (NSString *)getIndexTimeString:(NSInteger)time{
    NSDateFormatter *stampFormatter = [[NSDateFormatter alloc] init];
    [stampFormatter setDateFormat:@"yyyy/MM/dd"];
    //以 1970/01/01 GMT为基准，然后过了secs秒的时间
    NSDate *stampDate2 = [NSDate dateWithTimeIntervalSince1970:time];
    return [stampFormatter stringFromDate:stampDate2];
}

//设置返回按钮
//+(void)setBackButton:(UIViewController*)uiviewcontroller navigationItem:(UINavigationItem *)navigationItem selector:(SEL)selector
//{
//    UIBarButtonItem *back = [PBFlatBarButtonItems backBarButtonItemWithTarget:uiviewcontroller selector:selector];
//    //OKBarButtonItemWithTarget
//    //    UIBarButtonItem *back = [PBFlatBarButtonItems OKBarButtonItemWithTarget:uiviewcontroller imagename:[UIImage imageNamed:@"back"] selector:selector];
//    [navigationItem setLeftBarButtonItem:back];
//}

//+(BOOL)isReachable:(UIView*)targetView
//{
//    //如果网络不可用，则取消所有正在执行的请求
//    if (![ApplicationDelegate.apiEngine isReachable])
//    {
//        [MBProgressHUD hideAllHUDsForView:targetView animated:YES];
//        [ShowMessage showTextOnly:@"当前网络不可用，请检查网络设置" messageView:targetView];
//        [ApplicationDelegate.apiEngine cancelAllOperations];
//        return NO;
//    }
//    return YES;
//}

+ (NSString *) md5:(NSString*)str
{
    const char *cStr = [str UTF8String];
        unsigned char result[16];
        CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
        return [NSString  stringWithFormat:
                @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                result[0], result[1], result[2], result[3],
                result[4], result[5], result[6], result[7],
                result[8], result[9], result[10], result[11],
                result[12], result[13], result[14], result[15]];
}
+ (UIColor *)UIColorFromRGB: (NSInteger)rgbValue {
    
    UIColor *rgbColor;
    
    rgbColor = [UIColor colorWithRed: ((float)((rgbValue & 0xFF0000) >> 16)) / 255.0
                               green: ((float)((rgbValue & 0xFF00) >> 8)) / 255.0
                                blue: ((float)(rgbValue & 0xFF)) / 255.0
                               alpha: 1.0];
    
    return rgbColor;
}
+(BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}
/**
 @abstract  返回字符串的高度。
 @discussion <#statements#>
 @since <#statements#>
 */
+ (CGSize)boundingRectWithSize:(CGSize)size strText:(NSString*)strText font:(UIFont*)font
{
    NSDictionary *attribute = @{NSFontAttributeName: font};
    
    CGSize retSize = [strText boundingRectWithSize:size
                                           options:\
                      NSStringDrawingTruncatesLastVisibleLine |
                      NSStringDrawingUsesLineFragmentOrigin |
                      NSStringDrawingUsesFontLeading
                                        attributes:attribute
                                           context:nil].size;
    
    return retSize;
}
/**
 @abstract 得到当前时间。
 @discussion <#statements#>
 @since <#statements#>
 */
+(NSString *)getCurrentDate
{
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [dateFormatter stringFromDate:[NSDate date]];
}
/** @abstract 转成String */
+(NSString*) idToString:(id)obj
{
    if ( obj == nil ) {
        return nil;
    }
    
    if ( [obj isKindOfClass:[NSNull class]]) {
        return nil;
    }
    
    if ( [obj isKindOfClass:[NSString class]]) {
        return (NSString*)obj;
    }else if ( [obj isKindOfClass:[NSArray class]] ){
        NSMutableString* ntf = [NSMutableString string];
        for (id t in obj ) {
            [ntf appendString:[self idToString:t]];
            [ntf appendString:@","];
        }
        return ntf;
    }else {
        if( CFGetTypeID((__bridge CFTypeRef)(obj)) == CFBooleanGetTypeID() ){
            return [NSString stringWithFormat:@"%@", (CFBooleanGetValue((CFBooleanRef)obj) == true ? @"true" : @"false") ];
        }
        if ( sizeof(obj) == sizeof(BOOL) ) {
            //return (BOOL)obj == YES ? @"true" : @"false";
        }
        if( [obj respondsToSelector:@selector(stringValue)] ){
            return [obj stringValue];
        }
        return [obj description];
    }
}
#pragma mark -  DES 加密、解密
/**@abstract DES 加密*/
+ (NSString *) encryptStr:(NSString *) str
{
    return[Utility doCipher:str key:_key context:kCCEncrypt];
}
/**@abstract DES 解密*/
+ (NSString *) decryptStr:(NSString *) str
{
    return[Utility doCipher:str key:_key context:kCCDecrypt];
}
/**@abstract DES 加密、解密*/
+ (NSString *)doCipher:(NSString *)sTextIn key:(NSString *)sKey
               context:(CCOperation)encryptOrDecrypt {
    NSStringEncoding EnC = NSUTF8StringEncoding;
    
    NSMutableData * dTextIn;
    if (encryptOrDecrypt == kCCDecrypt) {
        dTextIn = [[Utility decodeBase64WithString:sTextIn] mutableCopy];
    }
    else{
        dTextIn = [[sTextIn dataUsingEncoding: EnC] mutableCopy];
    }
    NSMutableData * dKey = [[sKey dataUsingEncoding:EnC] mutableCopy];
    [dKey setLength:kCCBlockSizeDES];
    uint8_t *bufferPtr1 = NULL;
    size_t bufferPtrSize1 = 0;
    size_t movedBytes1 = 0;
    //uint8_t iv[kCCBlockSizeDES];
    //memset((void *) iv, 0x0, (size_t) sizeof(iv));
    const void *vinitVec = (const void *) [_key UTF8String];
    bufferPtrSize1 = ([sTextIn length] + kCCKeySizeDES) & ~(kCCKeySizeDES -1);
    bufferPtr1 = malloc(bufferPtrSize1 * sizeof(uint8_t));
    memset((void *)bufferPtr1, 0x00, bufferPtrSize1);
    CCCrypt(encryptOrDecrypt, // CCOperation op
            kCCAlgorithmDES, // CCAlgorithm alg
            kCCOptionPKCS7Padding, // CCOptions options
            [dKey bytes], // const void *key
            [dKey length], // size_t keyLength
            vinitVec, // const void *iv
            [dTextIn bytes], // const void *dataIn
            [dTextIn length], // size_t dataInLength
            (void*)bufferPtr1, // void *dataOut
            bufferPtrSize1, // size_t dataOutAvailable
            &movedBytes1); // size_t *dataOutMoved
    
    
    NSString * sResult;
    if (encryptOrDecrypt == kCCDecrypt){
        sResult = [[ NSString alloc] initWithData:[NSData dataWithBytes:bufferPtr1
                                                                 length:movedBytes1] encoding:EnC] ;
    }
    else {
        NSData *dResult = [NSData dataWithBytes:bufferPtr1 length:movedBytes1];
        sResult = [Utility encodeBase64WithData:dResult];
    }
    return sResult;
}
#pragma mark - Base64加密
/**@abstract Base64 加密*/
+ (NSString *)encodeBase64WithString:(NSString *)strData {
    return[Utility encodeBase64WithData:[strData dataUsingEncoding:NSUTF8StringEncoding]];
}

/**@abstract Base64 加密*/
+ (NSString *)encodeBase64WithData:(NSData *)objData {
    const unsigned char * objRawData = [objData bytes];
    char * objPointer;
    char * strResult;
    
    // Get the Raw Data length and ensure we actually have data
    NSInteger intLength = [objData length];
    if (intLength == 0) return nil;
    
    // Setup the String-based Result placeholder and pointer within that placeholder
    strResult = (char *)calloc(((intLength + 2) / 3) * 4, sizeof(char));
    objPointer = strResult;
    
    // Iterate through everything
    while(intLength > 2) { // keep going until we have less than 24 bits
        *objPointer++ = _base64EncodingTable[objRawData[0] >> 2];
        *objPointer++ = _base64EncodingTable[((objRawData[0] & 0x03) << 4) + (objRawData[1] >> 4)];
        *objPointer++ = _base64EncodingTable[((objRawData[1] & 0x0f) << 2) + (objRawData[2] >> 6)];
        *objPointer++ = _base64EncodingTable[objRawData[2] & 0x3f];
        
        // we just handled 3 octets (24 bits) of data
        objRawData += 3;
        intLength -= 3;
    }
    
    // now deal with the tail end of things
    if (intLength != 0) {
        *objPointer++ = _base64EncodingTable[objRawData[0] >> 2];
        if (intLength > 1) {
            *objPointer++ = _base64EncodingTable[((objRawData[0] & 0x03) << 4) + (objRawData[1] >> 4)];
            *objPointer++ = _base64EncodingTable[(objRawData[1] & 0x0f) << 2];
            *objPointer++ = '=';
        } else {
            *objPointer++ = _base64EncodingTable[(objRawData[0] & 0x03) << 4];
            *objPointer++ = '=';
            *objPointer++ = '=';
        }
    }
    
    // Terminate the string-based result
    *objPointer = '\0';
    
    // Return the results as an NSString object
    return[NSString stringWithCString:strResult encoding:NSASCIIStringEncoding];
}
/**@abstract Base64 解密*/
+ (NSData *)decodeBase64WithString:(NSString *)strBase64 {
    const char* objPointer = [strBase64 cStringUsingEncoding:NSASCIIStringEncoding];
    NSInteger intLength = strlen(objPointer);
    int intCurrent;
    int i = 0, j = 0, k;
    
    unsigned char * objResult;
    objResult = calloc(intLength, sizeof(char));
    
    // Run through the whole string, converting as we go
    while ( ((intCurrent = *objPointer++) != '\0') && (intLength-- > 0) ) {
        if (intCurrent == '=') {
            if (*objPointer != '=' && ((i % 4) == 1)) {// || (intLength > 0)) {
                // the padding character is invalid at this point -- so this entire string is invalid
                free(objResult);
                return nil;
            }
            continue;
        }
        
        intCurrent = _base64DecodingTable[intCurrent];
        if (intCurrent == -1) {
            // we're at a whitespace -- simply skip over
            continue;
        } else if (intCurrent == -2) {
            // we're at an invalid character
            free(objResult);
            return nil;
        }
        
        switch (i % 4) {
            case 0:
                objResult[j] = intCurrent << 2;
                break;
                
            case 1:
                objResult[j++] |= intCurrent >> 4;
                objResult[j] = (intCurrent & 0x0f) << 4;
                break;
                
            case 2:
                objResult[j++] |= intCurrent >>2;
                objResult[j] = (intCurrent & 0x03) << 6;
                break;
                
            case 3:
                objResult[j++] |= intCurrent;
                break;
        }
        i++;
    }
    
    // mop things up if we ended on a boundary
    k = j;
    if (intCurrent == '=') {
        switch (i % 4) {
            case 1:
                // Invalid state
                free(objResult);
                return nil;
                
            case 2:
                k++;
                // flow through
            case 3:
                objResult[k] = 0;
        }
    }
    
    // Cleanup and setup the return NSData
    NSData * objData = [[NSData alloc] initWithBytes:objResult length:j];
    free(objResult);
    return objData;
}
#pragma mark - URL编码
/** @abstract 字符串编码 */
+(NSString *)StringEncode:(NSString*)str
{
    if (!str.length)
        return str;
    
    NSMutableString * output = [NSMutableString string];
    const char * source = (const char *)[str UTF8String];
    unsigned long sourceLen = strlen((const char *)source);
    for (int i = 0; i < sourceLen; ++i) {
        const unsigned char thisChar = source[i];
        if (thisChar == ' '){
            [output appendString:@"+"];
        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
                   (thisChar >= 'a' && thisChar <= 'z') ||
                   (thisChar >= 'A' && thisChar <= 'Z') ||
                   (thisChar >= '0' && thisChar <= '9')) {
            [output appendFormat:@"%c", thisChar];
        } else {
            [output appendFormat:@"%%%02X", thisChar];
        }
    }
    return output;
}
/** @abstract URL编码 */
+ (NSString *)URLEncode:(NSString*)baseUrl data:(NSDictionary*)dictionary
{
    NSString *url = baseUrl;
    if(url.length)
    {
        url = [url stringByAppendingString:@"?"];
    }
    else
    {
        url = @"";
    }
    
    BOOL isFirst = YES;
    for(NSString *key in dictionary.allKeys)
    {
        if(isFirst)
        {
            isFirst = NO;
        }
        else
        {
            url = [url stringByAppendingString:@"&"];
        }
        url = [url stringByAppendingFormat:@"%@=%@", [NSString stringWithFormat:@"%@", [self StringEncode:key]], [self StringEncode:[NSString stringWithFormat:@"%@", [dictionary objectForKey:key]]]];
    }
    return url;
}
#pragma mark - 序列化参数字典（进行URL编码）
/** @abstract 序列化参数字典（进行URL编码） */
+(NSMutableDictionary*)ParamEncodeByDic:(NSMutableDictionary*)dictionary
{
    if (dictionary==nil)
        return nil;
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    for(NSString *key in dictionary.allKeys)
    {
        NSString *strValue= [self StringEncode:[NSString stringWithFormat:@"%@",[dictionary objectForKey:key]]];
        NSString *strKey=[NSString stringWithFormat:@"%@", [self StringEncode:key]];
        [dic setObject:strValue forKey:strKey];
        
    }
    
    return dic;
}


/**
 *  判断是否邮箱
 *
 *  @param email <#email description#>
 *
 *  @return <#return value description#>
 */
+ (BOOL)isValidateEmail:(NSString *)email {
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:email];
    
}



#pragma mark - 正则获取url参数
/**
 @abstract 正则获取url参数。
 @discussion <#statements#>
 @since <#statements#>
 */
+(NSString *) getParamValue:(NSString *)CS webaddress:(NSString *)webaddress
{
    NSError *error;
    NSString *regTags=[[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)",CS];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    
    // 执行匹配的过程
    NSArray *matches = [regex matchesInString:webaddress options:0
                                        range:NSMakeRange(0, [webaddress length])];
    for (NSTextCheckingResult *match in matches) {
        //NSRange matchRange = [match range];
        //NSString *tagString = [webaddress substringWithRange:matchRange];  // 整个匹配串
        //        NSRange r1 = [match rangeAtIndex:1];
        //        if (!NSEqualRanges(r1, NSMakeRange(NSNotFound, 0))) {    // 由时分组1可能没有找到相应的匹配，用这种办法来判断
        //            //NSString *tagName = [webaddress substringWithRange:r1];  // 分组1所对应的串
        //            return @"";
        //        }
        
        NSString *tagValue = [webaddress substringWithRange:[match rangeAtIndex:2]];  // 分组2所对应的串
        //    NSLog(@"分组2所对应的串:%@\n",tagValue);
        return tagValue;
    }
    return @"";
}


#pragma mark - 判断是否安装过某个APP
+(BOOL)  APCheckIfAppInstalled2:(NSString *)urlSchemes
{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlSchemes]])
    {
        NSLog(@" installed");
        
        return  YES;
    }
    else
    {
        return  NO;
    }
}

#pragma mark - 参数签名加密
//7 返回拼接字符串
//7 返回拼接字符串
+(NSMutableDictionary *)createTokenJoinByDic:(NSMutableDictionary *)dic
{
    if (dic==nil)
        dic=[NSMutableDictionary dictionary];
    
    if ([dic objectForKey:@"sign"])
    {
        [dic removeObjectForKey:@"sign"];
    }
    //    System_Version_Code;
    //    System_ApiType_Code;
    
    //    if (isAddLoginToken) {
    //
    //        NSUserDefaults *loginToken = [NSUserDefaults standardUserDefaults];
    //        [dic setObject:[NSString stringWithFormat:@"%@",[loginToken objectForKey:@"loginToken"]] forKey:@"loginToken"];
    //    }
    //随机数
    NSString *str_random = [NSString stringWithFormat:@"%u#%u",(arc4random() % 9999) + 1000,(arc4random() % 9999) + 1000];
    [dic setObject:str_random forKey:@"random"];
    
    
    /**
     *  获取设置字典的Key数组
     */
    NSArray *arr_keypre= [dic allKeys];
    //数组block排序(按照字母升序排序)
    NSArray *arr_sort = [arr_keypre sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSComparisonResult result = [obj1 compare:obj2];
        return result;
    }];
    
    
    NSMutableArray *arr_key = [NSMutableArray arrayWithArray:arr_sort];
    
    
    //声明存储Key与Value的数组
    NSMutableArray *arry_dic = [NSMutableArray array];
    /**
     *  将Key与Value按照预先规则放入数组，进行String拼接
     */
    for (NSInteger i = 0; i < arr_key.count; i++) {
        NSString *str_key = arr_key[i];
        [arry_dic addObject:str_key];
        [arry_dic addObject:dic[str_key]];
    }
    //进行String拼接
    NSString *str_join_dic = [arry_dic componentsJoinedByString:@"#"];
    
    
    //设置密钥
    NSString *str_key = @"qUzYH3VvIcWP7jhk4QJDtrg0Xkuc4NuS";
    /**
     *  Token拼接规则，变量数组经过字母升序排列，进行遍历
     *  按照“[变量1#][变量1Value#][变量2#][变量2Value#][变量..#][变量..Value#]str_key”格式拼接
     */
    
    NSString *str_token = [str_join_dic stringByAppendingString:[@"#" stringByAppendingString:str_key]];
    
    
    [dic setObject:[self md5:str_token] forKey:@"sign"];
    
    
    NSLog(@"************");
    NSLog(@"***拼接字典是：%@\n%@\n%@",str_token,dic,[self md5:str_token]);
    NSLog(@"************");
    return dic;
    
}




#pragma mark - 通过字典获取Model
/**
 *  @author EricWei, 2016-03-31 14:03:33
 *  @abstract 通过字典获取Model
 *
 *  通过字典获取Model
 *
 *  @param dic <#dic description#>
 *
 *  @return <#return value description#>
 */
//+(id)getModelFromDic:(NSDictionary*)dic  Cls:(Class)cls
//{
//    return [RMMapper objectWithClass:cls fromDictionary:dic];
//}
/**
 
 *  URLEncode
 
 */

+ (NSString *)URLEncodedString:(NSString *)url

{
    
    // CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
    
    // CharactersToLeaveUnescaped = @"[].";
    
    
    
    NSString *unencodedString = url;
    
    NSString *encodedString = (NSString *)
    
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              
                                                              (CFStringRef)unencodedString,
                                                              
                                                              NULL,
                                                              
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
    
}
+ (UIColor *)colorWithHexString: (NSString *)color {
    
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    if ([cString length] < 6) { return [UIColor clearColor]; }
    // 判断前缀
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    // 从六位数值中找到RGB对应的位数并转换
    NSRange range;
    range.location = 0;
    range.length = 2;
    //R、G、B
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values unsigned
    int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
    
}
/**
 获取字符串的高度 s:string  f:font  w:width

 @param s <#s description#>
 @param f <#f description#>
 @param w <#w description#>
 @return <#return value description#>
 */
+ (CGFloat)String:(NSString *)s Font:(CGFloat)f Width:(CGFloat)w{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    NSDictionary * attributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:f], NSParagraphStyleAttributeName: paragraphStyle };
    CGSize textRect = CGSizeMake(w, MAXFLOAT);
   return  [s boundingRectWithSize: textRect options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:attributes context:nil].size.height;
}


@end

